import { useCallback, useContext, useMemo, useState } from "react";
import { Table, Button, Modal,Form, Image } from "antd";
import EditRouteLine from "./EditRouteLine";
import { Service } from "@/lib";
import defaultImage from "../../../../img/defaultImg.gif";
const RouteLines = ({ value, onChange, disabled }: any) => {
    const [ form ] = Form.useForm();

    const [ srcLines ] = useState( () => (value || []).map((item: any) => ({ ...item, operateStatus: 0 })));
    const [ routeLines, setRouteLines ] = useState<any[]>(srcLines.map((item: any, index: number)=>({ ...item, index })));
    const tableData = useMemo(() => routeLines.filter((item: any) => (item.operateStatus != 3)
        ), [routeLines]);
    
    const [ editState, setEditState ] = useState<any>({
        show: false,
        data: {}
    }); 
      const serviceApi = Service.useService();
    const [ imgPref ] = useState(() => serviceApi.getUrl("resource.mediaUrl"));

    const formatImageUrl = useCallback((value: string) => {
        return value ? imgPref + "/" + value : defaultImage;
    }, []);
     const onEditSave = useCallback(() => {
        
        form.validateFields().then((frmData) => {
            const newList = [ ...routeLines ].map((item) => {
                return (frmData.id && item.id === frmData.id) || (!frmData.id && !frmData.index && frmData.index === item.index) ? {
                    ...item,
                    ...frmData,
                    images: JSON.stringify(frmData.images || []),
                    operateStatus: item.id ? 2 : 1
                } : item;
            });
            if(!frmData.id && (frmData.index === null || frmData.index === undefined)) {
                newList.push({
                    ...frmData,
                    images: JSON.stringify(frmData.images || []),
                    operateStatus: 1,
                    index: newList.length });
            }
            typeof onChange === "function" && onChange(newList);
            setRouteLines(newList);console.log(newList);
            setEditState({
                show: false,
                data: {}
            });
        }).catch((err) => {
            console.error(err);
        });
    }, [form, routeLines, onChange]);
    const columns = useMemo(() => ([
        {
            title: "路线点位名称",
            dataIndex: "title",
            key: "id",
            width: 200
        }, {
            title: "详细地址",
            dataIndex: "addr",
            key: "location",
            width: 300
        }, {
            title: "研学点位主图",
            dataIndex: "cover",
            render: (val: string) => {
                return <Image src={formatImageUrl(val)} alt="" width={80} height={80} />
            }
        },{
            title: "排序",
            dataIndex: "sortId",
            width: 60
        },{
            title: "操作",
            dataIndex: "id",
            render: (_: string, data: any) => {
                return (<>
                    { !disabled && <Button type="primary" size="small" onClick={() => {
                        form.setFieldsValue({
                            title: data.title || "",
                            addr: data.addr ||"",
                            description: data.description || "",
                            cover: data.cover || "",
                            images: JSON.parse(data.images || "[]"),
                            index: data.index,
                            id: data.id,
                            sortId: data.sortId
                        });
                        setEditState({
                            show: true,
                            data
                        });
                    }}>编辑</Button> }
                    { disabled && <a style={{marginRight: 10}} onClick={() => {
                        form.setFieldsValue({
                            title: data.title || "",
                            addr: data.addr ||"",
                            description: data.description || "",
                            cover: data.cover || "",
                            images: JSON.parse(data.images || "[]"),
                            index: data.index,
                            id: data.id,
                            sortId: data.sortId
                        });
                        setEditState({
                            show: true,
                            data
                        });
                    }}>查看</a> }
                    <Button type="dashed" size="small" onClick={() => {
                        const newList: any[] = [];
                        for(const item of routeLines) {
                            if(item.index === data.index) {
                                if(item.id) {
                                    newList.push({
                                        ...item,
                                        operateStatus: 3
                                    })
                                }
                            } else {
                                newList.push({ ...item });
                            }
                        }
                        setRouteLines(newList);
                        typeof onChange === "function" && onChange(newList);
                    }}>删除</Button>
                </>);
            }
        }
    ]), [onEditSave, routeLines, onChange]);

    return (
        <section>
            <Button type="primary" onClick={() => {
                form.setFieldsValue({
                    title: "",
                    addr: "",
                    description: "",
                    cover: "",
                    images: [],
                    index: null
                });
                setEditState({
                    show: true,
                    data: {}
                });
            }}>新增线路点</Button>
            <Table
                columns={columns}
                dataSource={tableData}
            />
            {editState.show && <Modal
                title={editState.data?.id ? "编辑线路点信息" : "添加线路点信息"}
                okText="确定"
                cancelText="取消"
                open
                onOk={() => {
                    return onEditSave();
                }}
                onCancel={() => {
                    setEditState({
                        show: false,
                        data: {}
                    });
                }}
                destroyOnClose
                okButtonProps={{
                    style: {
                        display: disabled ? "none" : ""
                    }
                }}
            >
                <EditRouteLine data={editState.data} form={form} disabled={disabled}/>
            </Modal> }
        </section>
    );
};

export default RouteLines;